package com.zrt.pad.commonui.task;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.widget.ImageView;

import com.zrt.pad.commonui.SharedApplication;
import com.zrt.pad.datasource.DataSourceInstance;
import com.zrt.pad.datasource.OptionName;

public class DownloadImageTask {

	private static List<String> imageList;
	private static List<String> downloadingList;
	private static File parent;
	
	private static Handler handler;
	
	static {
		Context context = SharedApplication.context;
		parent = context.getDir("ImgCache", Context.MODE_PRIVATE);
		String[] imgFiles = parent.list(new FilenameFilter() {
			
			@Override
			public boolean accept(File dir, String filename) {
				return filename.toLowerCase(Locale.CHINA).endsWith(".jpg");
			}
		});
		imageList = new ArrayList<String>(Arrays.asList(imgFiles));
		downloadingList = new ArrayList<String>();
		
		handler = new Handler(Looper.getMainLooper());
	}
	
	private DownloadImageTask(){}
	
	public static final DownloadImageTask task = new DownloadImageTask();
	
	public void download(ImageView iv, String name){
		Holder h = new Holder();
		h.imageName = name;
		h.displayView = iv;
		DownloadWorker dw = new DownloadWorker();
		dw.data = h;
		new Thread(dw).start();
	}
	
	public void tryLoadImage(ImageView iv, String name){
		if (imageList.contains(name+".jpg")) {
			File imgFile = new File(parent, name+".jpg");
			Drawable image = Drawable.createFromPath(imgFile.getAbsolutePath());
			if (image == null) {
				imgFile.delete();
			} else {
				image.setBounds(0, 0, iv.getWidth(), iv.getHeight());
				iv.setImageDrawable(image);
			}
			return;
		}
		if (downloadingList.contains(name)) {
			return;
		}
		download(iv, name);
	}
	
	private class Holder {
		ImageView displayView;
		String imageName;
	}
	
	private class DownloadWorker implements Runnable{

		public Holder data;
		
		@Override
		public void run() {
			synchronized (downloadingList) {
				downloadingList.add(data.imageName);
			}
			File tmpFile = new File(parent, data.imageName+".tmp");
			File destFile = new File(parent, data.imageName+".jpg");
			try {
				tmpFile.createNewFile();
				FileOutputStream fos = new FileOutputStream(tmpFile);
				
                //byte[] img = NetworkManager.nm.GetPluImageInfo(data.imageName);
                //fos.write(img);
				String url = DataSourceInstance.instance.getOption(OptionName.SERVER_IP);
				if (!url.endsWith("/")) {
					url += "/";
				}
				url = "http://"+ url +"padimage/" + data.imageName + "/1.jpg";
				InputStream is = new URL(url).openStream();
				byte[] buffer = new byte[1024];
				while (true) {
					int length = is.read(buffer);
					if (length == -1) {
						break;
					}
					fos.write(buffer, 0, length);
				}
				fos.close();
				tmpFile.renameTo(destFile);
				
				synchronized (imageList) {
					imageList.add(data.imageName);
				}
				
				Drawable image = Drawable.createFromPath(destFile.getAbsolutePath());
				if (image != null) {
					image.setBounds(0, 0, data.displayView.getWidth(), data.displayView.getHeight());
					handler.post(new ChangeImage(data.displayView, image));
				} else {
					destFile.delete();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e){
				e.printStackTrace();
			}
			finally {
				synchronized (downloadingList) {
					downloadingList.remove(data.imageName);
				}
			}
		}
		
	}
	
	private class ChangeImage implements Runnable{

		private ImageView v;
		private Drawable d;
		
		public ChangeImage(ImageView v, Drawable d){
			this.v = v;
			this.d = d;
		}
		@Override
		public void run() {
			if (v.isShown()) {
				v.setImageDrawable(d);
			}
		}
		
	}
	
}
